package com.treeroot.treenet.protocol.abs.tcp.session;

import com.treeroot.treenet.protocol.abs.tcp.decode.FrameDecoder;
import com.treeroot.treenet.protocol.abs.tcp.route.MessageRouter;
import lombok.Data;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Description: tcp会话
 * Create By TreeRoot
 * Create Time: 2025/06/02 08:25
 * Class Name: TcpSession
 *
 * @author TreeRoot
 */
@Data
@SuppressWarnings("unused")
public class TcpSession {

    private static final Logger log = LoggerFactory.getLogger(TcpSession.class);
    private WriteBufferQueue writeBufferQueue;
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    private SelectionKey key;
    private String acceptIp;
    private SocketChannel clientChannel;
    private String channelId;
    private FrameDecoder frameDecoder;
    private MessageRouter router;

    /**
     * 获取上次心跳时间
     */
    @Getter
    private volatile long lastHeartbeatTime = System.currentTimeMillis();


    public TcpSession(ServerSocketChannel serverSocketChannel, Selector selector, SelectionKey key, String acceptIp,
                      SocketChannel clientChannel, String channelId, long lastHeartbeatTime) {
        this.serverSocketChannel = serverSocketChannel;
        this.selector = selector;
        this.key = key;
        this.acceptIp = acceptIp;
        this.clientChannel = clientChannel;
        this.channelId = channelId;
        this.lastHeartbeatTime = lastHeartbeatTime;
    }

    public TcpSession() {
    }

    public TcpSession(ServerSocketChannel serverSocketChannel, Selector selector, SelectionKey key) {
        this.serverSocketChannel = serverSocketChannel;
        this.selector = selector;
        this.key = key;
    }

    public void send(ByteBuffer data) {
        writeBufferQueue.offer(data);
    }

    public String createChannelId() {
        String ip = acceptIp.replaceFirst("^/", "");
        return clientChannel.hashCode() + "_" + System.nanoTime() + "_" + ip;
    }

    public void updateHeartbeat() {
        lastHeartbeatTime = System.currentTimeMillis();
    }

    /**
     * 关闭连接，释放资源
     */
    public void close() {
        try {
            if (key != null) {
                key.cancel();
            }
            if (clientChannel != null) {
                clientChannel.close();
            }
        } catch (IOException e) {
            log.error("HandleUdpRequest.close", e);
        }
    }

    /**
     * 销毁这个类
     */
    public void destroy() {
        close();
    }
}